// API 基础配置
import { LocalStorage } from "@/utils/storage";
import { API_BASE_URL } from "@/config/api";

// HTTP 请求工具类
class ApiClient {
  private baseURL: string;
  private token: string | null;

  constructor(baseURL: string) {
    this.baseURL = baseURL;
    // 使用LocalStorage工具类获取token
    this.token = LocalStorage.getTokenFromStorage();
  }

  setToken(token: string | null) {
    this.token = token;
    // 注意：这里不再直接操作localStorage，让LocalStorage工具类来处理
    // 因为它需要根据记住登录状态决定存储位置
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {},
  ): Promise<{ success: boolean; data?: T; message: string; code?: string }> {
    const url = `${this.baseURL}${endpoint}`;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...(options.headers as Record<string, string>),
    };

    if (this.token) {
      headers.Authorization = `Bearer ${this.token}`;
    }

    try {
      const response = await fetch(url, {
        ...options,
        headers,
        credentials: "include",
      });

      let result;
      try {
        result = await response.json();
      } catch (e) {
        // 如果响应不是有效JSON（比如429错误返回的文本），创建错误对象
        if (response.status === 429) {
          result = {
            success: false,
            message: "请求过于频繁，请稍后再试",
            code: "TOO_MANY_REQUESTS",
          };
        } else {
          result = {
            success: false,
            message: `服务器错误 (${response.status})`,
            code: "SERVER_ERROR",
          };
        }
      }

      if (!response.ok) {
        // 如果是401未授权错误，清理token
        if (response.status === 401) {
          this.setToken(null);
          // 发送自定义事件通知登录状态失效
          window.dispatchEvent(
            new CustomEvent("auth:unauthorized", {
              detail: { status: response.status, message: result.message },
            }),
          );
        }

        // 如果是429错误，提供友好的错误信息
        if (response.status === 429) {
          throw new Error("请求过于频繁，请稍后再试");
        }

        throw new Error(result.message || `HTTP ${response.status}`);
      }

      return result;
    } catch (error) {
      console.error("API request failed:", error);
      throw error;
    }
  }

  async get<T>(endpoint: string): Promise<{ success: boolean; data?: T; message: string }> {
    return this.request<T>(endpoint, { method: "GET" });
  }

  async post<T>(
    endpoint: string,
    data?: Record<string, unknown>,
  ): Promise<{ success: boolean; data?: T; message: string }> {
    return this.request<T>(endpoint, {
      method: "POST",
      body: data ? JSON.stringify(data) : undefined,
    });
  }

  async put<T>(
    endpoint: string,
    data?: Record<string, unknown>,
  ): Promise<{ success: boolean; data?: T; message: string }> {
    return this.request<T>(endpoint, {
      method: "PUT",
      body: data ? JSON.stringify(data) : undefined,
    });
  }

  async delete<T>(endpoint: string): Promise<{ success: boolean; data?: T; message: string }> {
    return this.request<T>(endpoint, { method: "DELETE" });
  }
}

// 创建 API 客户端实例
export const apiClient = new ApiClient(API_BASE_URL);

// 导出类型定义
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message: string;
  code?: string;
}

export interface PaginatedResponse<T = any> {
  success: boolean;
  data: T[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  };
  message: string;
}
